<style lang="less">
    @import "appertainRegion.less";
</style>
<template>
    <div class="search">
        <Card>
            <Row class="operation">
                <Button @click="add" type="primary" icon="md-add">添加子区域</Button>
                <Button @click="addRoot" icon="md-add">添加一级区域</Button>
                <Button @click="delAll" icon="md-trash">批量删除</Button>
                <Button @click="getParentList" icon="md-refresh">刷新</Button>
            </Row>
            <Row type="flex" justify="start" class="code-row-bg">
                <Col span="8">
                    <Alert show-icon>
                        当前选择编辑： <span class="select-count">{{editTitle}}</span>
                        <a class="select-clear" v-if="form.id" @click="cancelEdit">取消选择</a>
                    </Alert>
                    <Input v-model="searchKey" suffix="ios-search" @on-change="search" placeholder="输入区域名搜索"/>
                    <div class="tree-bar">
                        <Tree ref="tree" :data="data" :load-data="loadData" show-checkbox
                              @on-check-change="changeSelect" @on-select-change="selectTree"></Tree>
                    </div>
                    <Spin size="large" fix v-if="loading"></Spin>
                </Col>
                <Col span="12">
                    <Form ref="form" :model="form" :label-width="85" :rules="menuFormValidate">
                        <FormItem label="上级区域" prop="parentTitle">
                            <Poptip trigger="click" placement="right-start" title="选择上级区域" width="250">
                                <Input v-model="form.parentTitle" readonly style="width: 200px"/>
                                <div slot="content" style="position:relative;min-height:5vh">
                                    <Tree :data="dataEdit" :load-data="loadData"
                                          @on-select-change="selectTreeEdit"></Tree>
                                    <Spin size="large" fix v-if="loadingEdit"></Spin>
                                </div>
                            </Poptip>
                        </FormItem>
                        <FormItem v-if="this.fromFlag ==='0'" label="区域编号" prop="code">
                            <Input v-model="form.code" style="width: 200px"/>
                        </FormItem>
                        <FormItem v-if="this.fromFlag ==='1'" label="区域编号" prop="code">
                            <Input v-model="form.code" disabled style="width: 200px"/>
                        </FormItem>
                        <FormItem v-if="this.fromFlag ==='0'" label="区域名称" prop="title">
                            <Input v-model="form.title" style="width: 200px"/>
                        </FormItem>
                        <FormItem v-if="this.fromFlag ==='1'" label="区域名称" prop="localValue">
                            <Cascader :render-format="format" :load-data="loadDatas" :data="location"
                                      filterable change-on-select v-model="localValue" placeholder="下拉选择省市"
                                      @on-change="ChangeForm" style="width: 200px" :clearable="false">
                            </Cascader>
                        </FormItem>
                        <FormItem label="排序值" prop="sortOrder">
                            <InputNumber :max="1000" :min="0" v-model="form.sortOrder"></InputNumber>
                            <span style="margin-left:5px">值越小越靠前，支持小数</span>
                        </FormItem>
                        <FormItem label="是否启用" prop="status">
                            <Select
                                v-model="form.status"
                                placeholder="请选择"
                                clearable
                                style="width: 200px"
                            >
                                <Option value="1">正常</Option>
                                <Option value="0">禁用</Option>
                            </Select>
                        </FormItem>
                        <Form-item>
                            <Button style="margin-right:5px" @click="submitEdit" :loading="submitLoading" type="primary"
                                    icon="ios-create-outline">修改并保存
                            </Button>
                            <Button @click="cancelEdit">重置</Button>
                        </Form-item>
                    </Form>
                </Col>
            </Row>
        </Card>

        <Modal :title="modalTitle" v-model="menuModalVisible" :mask-closable='false' :width="500">
            <Form ref="formAdd" :model="formAdd" :label-width="85" :rules="menuFormValidate">
                <div v-if="showParent">
                    <FormItem label="上级区域：">
                        {{form.title}}
                    </FormItem>
                </div>
                <FormItem v-if="form.level !==3" label="区域编号" prop="code">
                    <Input v-model="formAdd.code" style="width: 200px"/>
                </FormItem>
                <FormItem v-if="form.level ===3" label="区域编号" prop="code">
                    <Input v-model="formAdd.code" disabled style="width: 200px"/>
                </FormItem>
                <FormItem v-if="form.level !==3" label="区域名称" prop="title">
                    <Input v-model="formAdd.title" style="width: 200px"/>
                </FormItem>
                <FormItem v-if="form.level ===3" label="区域名称" prop="localValue">
                    <Cascader :render-format="format" :load-data="loadDatas" :data="location"
                              filterable change-on-select v-model="localValue" placeholder="下拉选择省市"
                              @on-change="ChangeApp" style="width: 200px" :clearable="false">
                    </Cascader>
                </FormItem>
                <FormItem label="排序值" prop="sortOrder">
                    <InputNumber :max="1000" :min="0" v-model="formAdd.sortOrder"></InputNumber>
                    <span style="margin-left:5px">值越小越靠前，支持小数</span>
                </FormItem>
                <FormItem label="是否启用" prop="status">
                    <Select
                        v-model="formAdd.status"
                        placeholder="请选择"
                        clearable
                        style="width: 200px"
                    >
                        <Option value="1">正常</Option>
                        <Option value="0">禁用</Option>
                    </Select>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="cancelAdd">取消</Button>
                <Button type="primary" :loading="submitLoading" @click="submitAdd('formAdd')">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {
        getLocation,
        initAppertainRegion,
        addAppertainRegion,
        editAppertainRegion,
        deleteAppertainRegion,
        searchAppertainRegion,
        getAddressByCode
    } from "_p/afs-channel/api/admin/appertainRegion";

    export default {
        name: "develop-region",
        data() {
            return {
                loading: true,
                loadingEdit: true,
                menuModalVisible: false,
                selectList: [],
                selectCount: 0,
                showParent: false,
                modalTitle: "",
                editTitle: "",
                searchKey: "",
                selectFlag: "0",
                fromFlag: "0",
                location: [],
                localValue: [],
                form: {
                    id: "",
                    parentId: "",
                    parentTitle: "",
                    sortOrder: null,
                    status: 0,
                },
                formAdd: {},
                menuFormValidate: {
                    code: [{required: true, message: "编号不能为空", trigger: "blur"}],
                    title: [{required: true, message: "区域名称不能为空", trigger: "blur"}],
                },
                submitLoading: false,
                data: [],
                dataEdit: []
            };
        },
        methods: {
            init() {
                this.getParentList();
                this.getParentListEdit();
                this.getLocationData();
            },
            getParentList() {
                this.loading = true;
                let id = '0';
                initAppertainRegion(id).then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent === '1') {
                                e.loading = false;
                                e.children = [];
                            }
                        });
                        this.data = res.data;
                    }
                });
                this.cancelEdit();
            },
            getParentListEdit() {
                this.loadingEdit = true;
                let id = '0';
                initAppertainRegion(id).then(res => {
                    this.loadingEdit = false;
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent === '1') {
                                e.loading = false;
                                e.children = [];
                            }
                        });
                        // 头部加入一级
                        let first = {
                            id: "0",
                            title: "一级区域"
                        };
                        res.data.unshift(first);
                        this.dataEdit = res.data;
                    }
                });
            },
            loadData(item, callback) {
                initAppertainRegion(item.id).then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent === '1') {
                                e.loading = false;
                                e.children = [];
                            }
                        });
                        callback(res.data);
                    }
                });
            },
            search() {
                if (this.searchKey) {
                    this.loading = true;
                    searchAppertainRegion({title: this.searchKey}).then(res => {
                        this.loading = false;
                        if (res.code === "0000") {
                            this.data = res.data;
                        }
                    });
                } else {
                    this.getParentList();
                }
            },
            selectTree(v) {
                console.log(v)
                console.log("这个2")
                console.log(this.location)
                if (v.length > 0) {
                    // 转换null为""
                    for (let attr in v[0]) {
                        if (v[0][attr] === null) {
                            v[0][attr] = "";
                        }
                    }
                    let str = JSON.stringify(v[0]);
                    let data = JSON.parse(str);
                    if (data.level === 4) {
                        this.fromFlag = '1';

                    } else {
                        this.fromFlag = '0';
                    }
                    let item = {};
                    this.form = data;
                    this.localValue = data.code.split(',');
                    this.editTitle = data.title;
                    if(data.level == 4){
                        // 去查询这个code 的省市区
                        this.level(data.code);
                    }
                    console.log(this.localValue)
                } else {
                    this.cancelEdit();
                }
            },
            cancelEdit() {
                console.log("这个1")
                let data = this.$refs.tree.getSelectedNodes()[0];
                if (data) {
                    data.selected = false;
                }
                this.$refs.form.resetFields();
                delete this.form.id;
                this.editTitle = "";
                this.fromFlag = "0";
                this.form.title = "";
            },
            selectTreeEdit(v) {
                console.log("这个3")
                if (v.length > 0) {
                    // 转换null为""
                    for (let attr in v[0]) {
                        if (v[0][attr] === null) {
                            v[0][attr] = "";
                        }
                    }
                    let str = JSON.stringify(v[0]);
                    let data = JSON.parse(str);
                    this.form.parentId = data.id;
                    this.form.parentTitle = data.title;
                }
            },
            cancelAdd() {
                this.menuModalVisible = false;
            },
            submitEdit() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        if (!this.form.id) {
                            this.$Message.warning("请先点击选择要修改的区域");
                            return;
                        }
                        this.submitLoading = true;
                        if (this.form.sortOrder === null) {
                            this.form.sortOrder = "";
                        }
                        if (this.form.buttonType === null) {
                            this.form.buttonType = "";
                        }
                        editAppertainRegion(this.form).then(res => {
                            this.submitLoading = false;
                            if (res.code === "0000") {
                                this.$Message.success("编辑成功");
                                this.init();
                                this.menuModalVisible = false;
                            }
                        });
                    }
                });
            },
            getLocationData() {
                let param = ""
                param = {
                    level: '1',
                    upperCode: '1'
                };
                getLocation(param).then((res) => {
                    if (res.code == "0000") {
                        res.data.forEach(item => {
                            let obj = {
                                value: item.value,
                                label: item.label,
                                children: [],
                                level: 0,
                                loading: false
                            }
                            this.location.push(obj)
                        })
                    }
                })
            },
            loadDatas(item, callback) {
                console.log(item)
                console.log(callback)
                item.loading = true;
                let param = {
                    upperCode: item.value
                }
                getLocation(param).then(res => {
                    if (res.code == "0000") {
                        if(item.children.length>0){
                        console.log("之前加载过")
                        }else{
                            res.data.forEach(val => {
                            let obj = {
                                value: val.value,
                                label: val.label,
                            }
                            let templevel = parseInt(item.level);
                            // 当层级没有到最后一层
                            if ((templevel + 1) < (this.totalLevel - 1)) {
                                obj.children = [];
                                obj.level = templevel + 1;
                                obj.loading = false;
                            }
                            item.children.push(obj)
                        })
                        item.loading = false;
                        callback()
                        }
                        
                    }
                })
            },

            loadDatasLevel(code) {
                let param = {
                    upperCode: code
                }
                getLocation(param).then(res => {
                    if (res.code == "0000") {
                        for(var i=0; i<this.location.length;i++){
                            if(this.location[i].value==code){
                                if(this.location[i].children.length>0){
                                console.log("我已经有数据了！")
                                
                                }else{
                                    res.data.forEach(val => {
                                    let obj = {
                                        value: val.value,
                                        label: val.label,
                                    }
                                    let templevel = parseInt(this.location[i].level);
                                    // 当层级没有到最后一层
                                    if ((templevel + 1) < (this.totalLevel - 1)) {
                                        obj.children = [];
                                        obj.level = templevel + 1;
                                        obj.loading = false;
                                    }
                                    this.location[i].children.push(obj)
                                })
                                }
                            
                            }
                        }
                        
                        
                    }
                })
            },

            level(code) {
                let param = {
                    value: code
                }
                getAddressByCode(param).then(res => {
                    if (res.code == "0000") {
                         this.loadDatasLevel(res.data.upperCode);
                        this.localValue=[res.data.upperCode,res.data.value]
                    }
                })
            },
            format(labels, selectedData) {
                let index = labels.length - 1;
                let data = selectedData[index] || false;
                if (data && data.value) {
                    return labels[index]
                }
                return labels[index];
            },
            ChangeApp(value, v) {
                console.log(value)
                console.log(v)
                if (value && value.length > 0) {
                    this.formAdd.code = value[value.length - 1];
                } else {
                    this.formAdd.code = "";
                }
                if (v && v.length > 0) {
                    this.formAdd.title = v[v.length - 1].label;
                } else {
                    this.formAdd.title = "";
                }
            },
            ChangeForm(value, v) {
                if (value && value.length > 0) {
                    this.form.code = value[value.length - 1];
                } else {
                    this.form.code = "";
                }
                if (v && v.length > 0) {
                    this.form.title = v[v.length - 1].label;
                } else {
                    this.form.title = "";
                }
                console.log(this.localValue)
            },
            submitAdd(name) {
                if(this.formAdd.code==undefined||this.formAdd.code==null||this.formAdd.code==''){
                    this.$Message.warning("请填写编号");
                    return;
                }
                if(this.formAdd.title==undefined||this.formAdd.title==null||this.formAdd.title==''){
                    this.$Message.warning("请填写区域名称");
                    return;
                }
                        this.submitLoading = true;
                        if (this.formAdd.sortOrder === null) {
                            this.formAdd.sortOrder = "";
                        }
                        if (this.formAdd.buttonType === null) {
                            this.formAdd.buttonType = "";
                        }
                        addAppertainRegion(this.formAdd).then(res => {
                            this.submitLoading = false;
                            if (res.code === "0000") {
                                // 先清空一次之前的数据
                                this.data= [];
                                this.dataEdit= [];
                                this.location=[];
                                this.localValue= [];
                                this.$Message.success("添加成功");
                                this.init();
                                this.menuModalVisible = false;
                            }
                        });
                 
            },
            add() {
                if (this.form.id == "" || this.form.id == null) {
                    this.$Message.warning("请先点击选择一个区域");
                    return;
                }
                if (this.form.level === 4){
                    this.$Message.warning("不可添加");
                    return;
                }
                this.modalTitle = "添加子区域";
                this.selectFlag = '1';
                this.showParent = true;
                this.formAdd = {
                    parentId: this.form.id,
                    level: Number(this.form.level) + 1,
                    sortOrder: 1,
                    status: 0
                };
                this.menuModalVisible = true;
            },
            addRoot() {
                this.modalTitle = "添加一级区域";
                this.selectFlag = '0';
                this.showParent = false;
                this.formAdd = {
                    parentId: 0,
                    sortOrder: 1,
                    level: 1,
                    status: 0
                };
                this.menuModalVisible = true;
            },
            changeSelect(v) {
                this.selectCount = v.length;
                this.selectList = v;
            },
            delAll() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未勾选要删除的数据");
                    return;
                }
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = "";
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        deleteAppertainRegion(ids).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("删除成功");
                                this.selectList = [];
                                this.selectCount = 0;
                                this.cancelEdit();
                                this.init();
                            }
                        });
                    }
                });
            }
        },
        mounted() {
            this.init();
        }
    };
</script>
